package org.example.day1.mapper;

import org.apache.ibatis.annotations.*;
import org.example.day1.entity.Student;

import java.util.List;

@Mapper
public interface StudentMapper {
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "number", column = "no"),
            @Result(property = "sex", column = "sex"),
            @Result(property = "phone", column = "phone"),
            @Result(property = "qq", column = "qq")
    })
    @Select("select * from tb_student")
    List<Student> getAll();

    // 通过学号查询学生信息，去掉 @ResultMap，直接用 @Results
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "number", column = "no"),
            @Result(property = "sex", column = "sex"),
            @Result(property = "phone", column = "phone"),
            @Result(property = "qq", column = "qq")
    })
    @Select("select * from tb_student where no = #{no}")
    Student getStudentByNumber(String no);

    // 添加学生信息
    @Insert("insert into tb_student(no,name,sex,phone,qq) values(#{number},#{name},#{sex},#{phone},#{qq})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", resultType = Integer.class, before = false)
    int addStudent(Student student);



    // 通过学号查询学生信息，包含Card的信息
    @Select("SELECT * FROM tb_student WHERE no = #{no}")
    @Results(id = "studentMap2", value = {
            @Result(property = "number", column = "no"),
            @Result(property = "card", column = "no",
                    one = @One(select = "org.example.day1.mapper.CardMapper.getCardByCardNo")// 调用 CardMapper 接口中的方法
            )
    })
    Student getStudentByNumber2(String no);



    //通过学号或者姓名进行查询
    @ResultMap("studentMap")
//    @Select("select * from tb_student where no = #{number} or name = #{name}")
    //使用动态sql来实现
    @Select("<script>select * from tb_student where 1=1 " +
            "<if test='number != null'>and no = #{number}</if>" +
            "<if test='name != null'>and name = #{name}</if>" +
            "</script>")
//    假设学号为空，那么sql语句是："select * from tb_student where 1=1 and name = #{name}"
    List<Student> getStudentByNumberOrName(Student student);
}
